<template>
  <!-- 重编辑可视化弹窗 -->
  <!-- modified from /src/components/studio/data/drawer/VisualWindow.vue -->
  <modal-visualization
    :chart-config="oldItems"
    :visible="isModalVisible"
    @ok="handleOk"
    @cancel="handleCancel"
  />
  <!-- <div> -->
  <!-- <a-modal
      :destroy-on-close="true"
      :visible="isModalVisible"
      :width="1140"
      :centered="true"
      ok-text="确定"
      cancel-text="取消"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <div style="margin-top: -10px;">
        <span
          v-show="!titleModifiable"
          class="window-title"
          @click="setTitleModifiable"
          >{{
            currentGridItem &&
            currentGridItem.chartOptions &&
            currentGridItem.chartOptions.title
              ? currentGridItem.chartOptions.title
              : title
          }}
        </span>
        <a-input
          v-show="titleModifiable"
          v-model="tmpTitle"
          style="width: 100px;"
          @keyup.enter="inputToLabel"
          @blur="blur"
        >
        </a-input>
      </div>
      <div class="modal-content">
        <a-row>
          <a-col :span="5">
            <div class="window-left">
              <div style="font-weight: 600;">
                <div class="window-left-menubar">
                  组件列表
                </div>
                <div class="window-left-graphs">
                  <a-row>
                    <a-col :span="5">
                      <div
                        v-for="(vis, name) in visComponentClasses"
                        :key="name"
                      >
                        <div
                          class="window-left-buttons"
                          @click="selectGraphCategory(name)"
                        >
                          <img
                            class="left-icon"
                            :src="
                              publicPath +
                              vis.iconCharCode +
                              `${
                                selectedGraphCategory === name ? '-active' : ''
                              }` +
                              '.svg'
                            "
                            alt=""
                          />
                        </div>
                      </div>
                    </a-col>
                    <a-col :span="19">
                      <div class="window-content">
                        <div
                          v-for="(graph, index) in graphsCanBeSelected"
                          :key="index"
                          class="graph-box"
                          :class="{
                            'graph-selected': currentGraph === graph.name,
                          }"
                          @click="selectGraph(graph.name)"
                        >
                          <div class="window-content-graph">
                            <span style="color: #5d637e; margin: 6px;"
                              >{{ graph.title }}
                            </span>
                          </div>
                          <div class="window-content-imgs">
                            <img
                              :src="`${publicPath}${graph.imgSrc}`"
                              style="width: 100%;"
                            />
                          </div>
                        </div>
                      </div>
                    </a-col>
                  </a-row>
                </div>
              </div>
            </div>
          </a-col>
          <a-col :span="13">
            <div class="window-middle">
              <div class="window-middle-canvas">
                <Chart
                  v-if="chartVisible"
                  :chart-type="currentGraph"
                  :config="currentGridItem.chartOptions"
                ></Chart>
                <div v-else class="empty-info-box">
                  <img :src="currentChartEmptyImg" />
                  <div class="empty-info">请先配置数据</div>
                </div>
              </div>
            </div>
          </a-col>
          <a-col :span="6">
            <div class="window-right">
              <window-side-bar
                ref="windowSidebar"
                :chart-type="currentGraph"
                @change="onchange"
              />
            </div>
          </a-col>
        </a-row>
      </div>
    </a-modal> -->
  <!-- </div> -->
</template>

<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import DataViewStore from '@/store/modules/dataview'
import Chart from '@/components/chart/chart.vue'
import WindowSideBar from '@/components/studio/data/drawer/WindowSideBar.vue'
import { chartTypes, chartMaps } from '@/config/contant'
import { getWidgetJson } from '@/config/setting-chart'
import { cloneDeep } from 'lodash'
import { Watch, Prop } from 'vue-property-decorator'
import { publicPath } from '@/api/constants'
import ModalVisualization from '@/components/common/VisualizationDashboard/ModalVisualization.vue'

@Component({
  components: { Chart, WindowSideBar, ModalVisualization },
})
export default class VisualizationEditModal extends Vue {
  @Prop({ default: false }) isModalVisible!: boolean
  private widgetId: number = -1
  private tag = true // 标记当前窗口是新建窗口还是编辑窗口，false为新建，true为编辑
  private titleModifiable = false
  private tmpTitle = ''
  private title = ''
  private currentGridItem: any = null // 当前需要渲染的chart的一些配置信息
  private selectedGraphCategory = 'barChart' // 右侧选中的图的类别
  private currentGraph = 'barChart' // 当前选中的图
  private excludeGraphCategory = ['table']
  private publicPath = publicPath // 基础URL
  private commonConfig = {
    xAxisFontSize: 12,
    pointRadius: 3,
    padding: [10, 20, 10, 10],
    xAxisTitleFontSize: 14,
    yAxisTitleFontSize: 14,
    legendPosition: 'right',
    titleIsShow: true,
    titleFontSize: 18,
  }

  // 当前类别的图下面可以选择的具体图
  private graphsCanBeSelected: any = (chartMaps as any)[
    this.selectedGraphCategory
  ]

  private get allGraphs(): any {
    const data: any = cloneDeep(chartMaps)
    this.excludeGraphCategory.forEach((key) => {
      delete data[key]
    })
    return data
  }

  private get visComponentClasses() {
    const data = cloneDeep(chartTypes)
    this.excludeGraphCategory.forEach((key) => {
      delete data[key]
    })
    return data
  }

  setTitleModifiable() {
    this.titleModifiable = true
  }

  // 保存重命名
  inputToLabel() {
    this.title = this.tmpTitle
    this.titleModifiable = false
  }

  // 获取当前图表默认背景图片
  public get currentChartEmptyImg() {
    // const currentChart:any = flatten(Object.values(this.allGraphs)).find((item:any) => item.name === this.currentGraph)
    if (!this.graphsCanBeSelected) {
      return ''
    }
    const currentChart: any = this.graphsCanBeSelected.filter(
      (item: any) => item.name === this.currentGraph
    )[0]
    if (currentChart) {
      return this.publicPath + currentChart.imgSrc
    }
    return ''
  }

  public get visible() {
    return DataViewStore.getVisualWindowShow
  }

  public get selectNode(): any {
    return DataViewStore.selectNode
  }

  // 保存或者更新
  public handleOk(chartOptions: any) {
    // this.currentGridItem.chartType = [this.currentGraph, this.currentGraph]
    const data = {
      chartType: this.oldItems.chartType,
      chartOptions,
    }
    const postData = this.buildSaveParameters(data)
    if (this.tag) {
      this.$emit('ok', postData)
    }
    this.empty()
  }

  public handleCancel() {
    this.$emit('cancel')
    setTimeout(() => {
      this.empty()
    }, 200)
  }

  public empty() {
    this.currentGridItem = null
  }

  public onchange(item: any) {
    this.currentGridItem = {
      ...item,
    }
    this.tmpTitle = item.chartOptions.title
    if (this.currentGraph === 'stackBarChart') {
      // 不同图表类型下的额外配置，后续增加建议抽成独立的配置
      this.currentGridItem.chartOptions.barIsStack = true
    }
    if (this.currentGridItem.chartOptions.labelIsShow === undefined) {
      this.currentGridItem.chartOptions.labelIsShow = false
    }
    this.currentGridItem.chartOptions.size = [550, 400] // chart 大小
    this.currentGridItem.chartOptions = {
      ...this.commonConfig,
      ...this.currentGridItem.chartOptions,
    }

    if (
      [1, -1, '1', '-1'].includes(
        this.currentGridItem.chartOptions.value?.[0]?.label
      )
    ) {
      const abnormalIndex = this.currentGridItem.chartOptions.value.findIndex(
        (v: any) => [-1, '-1'].includes(v.label)
      )
      if (abnormalIndex > 0) {
        const [v] = this.currentGridItem.chartOptions.value.splice(
          abnormalIndex,
          1
        )
        this.currentGridItem.chartOptions.value = [
          v,
          ...this.currentGridItem.chartOptions.value,
        ]
      }
    }
    // console.error('this.currentGridItem.chartOptions', this.currentGridItem.chartOptions)
  }

  // 生成save接口需要的数据
  public buildSaveParameters(gridItem: any) {
    const chartOptions = cloneDeep({ ...gridItem.chartOptions, value: [] })
    // if (Array.isArray(chartOptions.geoLayer)) {
    //   chartOptions.geoLayer = chartOptions.geoLayer.map(
    //     (layer: any) => layer.type
    //   )
    // }
    chartOptions.isVisualization = false
    // gridItem.formData.value = []
    const result = {
      // formData: gridItem.formData,
      widgetJson: getWidgetJson(chartOptions),
      chartType: gridItem.chartType,
      x: gridItem.x,
      y: gridItem.y,
      w: gridItem.w,
      h: gridItem.h,
      i: gridItem.i,
      chartOptions,
    }
    return result
  }

  get chartVisible() {
    if (this.currentGridItem) {
      return true
    }
    return false
  }

  blur() {
    this.titleModifiable = false
    this.title = this.tmpTitle
    this.$set(this.currentGridItem, 'chartOptions', {
      ...this.currentGridItem.chartOptions,
      title: this.tmpTitle,
    })
    this.$set(this.currentGridItem, 'formData', {
      ...this.currentGridItem.chartOptions,
      title: this.tmpTitle,
    })
    // @ts-ignore
    this.$refs.windowSidebar.updateFormTitle(this.tmpTitle)
  }

  public created() {
    this.initByOldItem()
  }

  @Watch('isModalVisible')
  private onVisibleChange() {
    if (this.isModalVisible === true) {
      this.initByOldItem()
    }
  }

  private initByOldItem() {
    if (DataViewStore.getOldItems) {
      const oldItems = DataViewStore.getOldItems
      this.tag = true
      this.currentGraph = oldItems.chartType
      const index = Object.values(this.allGraphs).findIndex((category: any) =>
        category.some((item: any) => item.name === oldItems.chartType)
      )
      this.selectedGraphCategory = Object.keys(this.allGraphs)[index]
      this.graphsCanBeSelected = (chartMaps as any)[this.selectedGraphCategory]
      this.title = oldItems.name
      this.tmpTitle = this.title
      this.widgetId = oldItems.widgetId
    }
  }

  public selectGraphCategory(graphCategory: string) {
    this.selectedGraphCategory = graphCategory
    this.graphsCanBeSelected = (chartMaps as any)[this.selectedGraphCategory]
  }

  public selectGraph(graph: any) {
    this.currentGraph = graph
  }

  public get oldItems() {
    return DataViewStore.getOldItems
  }
}
</script>

<style lang="less" scoped>
.modal-content {
  background-color: #fff;
  height: 480px;
  margin: -24px;
  margin-top: 10px;
}

.content-text {
  color: #5d637e;
}

.graph-box {
  background-color: #fff;
  border: 1px solid;
  border-color: #e0e0e0;
  height: 100px;
  margin-top: 10px;
  width: 174px;
}

.graph-selected {
  border-color: #00f;
}

.window-title {
  display: inline-block;
  font-size: 120%;
  font-weight: 600;
  height: 32px;
}

.window-left {
  border: 1px solid #e0e0e0;
  border-bottom: 0;
  height: 480px;
}

.window-left-menubar {
  color: #5d637e;
  margin: 12px;
}

.window-left-graphs {
  border-top: 1px solid;
  border-top-color: #e0e0e0;
  height: 430px;
  width: 100%;
}

.window-left-buttons {
  background-color: #fff;
  border: 0;
  font-size: 25px;
  height: 45px;
  padding: 0 10px;
  width: 45px;

  .left-icon {
    width: 100%;
  }

  &:hover {
    background-color: fade(#f0f3ff, 50%);
    color: fade(#f9f9fc, 50%);
  }

  &:focus {
    background-color: fade(#5561ff, 15%);
    color: fade(#5561ff, 15%);
  }
}

.window-content {
  border-left: 1px solid;
  border-left-color: #e0e0e0;
  height: 430px;
  padding: 5px;
}

.window-content-graph {
  background-color: #f0f3ff;
  height: 26px;
}

.window-content-imgs {
  font-size: 20px;
  height: 70px;
  margin-left: 5px;
  margin-top: -5px;
  width: 160px;
}

.window-middle {
  background-color: #f6f6f6;
  border-top: 1px solid #e0e0e0;
  height: 480px;
}

.window-middle-canvas {
  background-color: #fff;
  height: 420px;
  margin: 30px;
  overflow: hidden;
  position: relative;

  .empty-info-box {
    height: 100%;
    text-align: center;

    img {
      margin-top: 50px;
      width: 80%;
    }
  }

  .empty-info {
    color: #999;
    position: relative;
  }
}

.window-right {
  border: 1px solid;
  border-color: #e0e0e0;
  height: 480px;
  overflow-y: scroll;
}
</style>
